package com.zff.rental.controller.user;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zff.rental.AppConstant;
import com.zff.rental.annotation.EnableVerifyToken;
import com.zff.rental.common.Result;
import com.zff.rental.entity.user.UserEntity;
import com.zff.rental.mapstruct.user.UserMapstruct;
import com.zff.rental.service.AdminService;
import com.zff.rental.service.user.UserServer;
import com.zff.rental.tools.JwtTools;
import com.zff.rental.vo.user.LoginParams;
import com.zff.rental.vo.user.LoginVo;
import com.zff.rental.vo.user.UserVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 用户
 *
 * @author HCY
 */
@RestController
@RequestMapping(AppConstant.RM_USER)
public class UserController {
    /**
     * 管理员服务
     */
    @Resource
    protected AdminService adminService;

    @Resource
    private UserServer userServer;

    /**
     * 手机号密码登录
     */
    @EnableVerifyToken(value = false)
    @PostMapping("/login")
    public Result<LoginVo> login(HttpServletResponse response, @RequestBody LoginParams loginParams) {
        UserEntity user = userServer.login(loginParams);
        return loginSuccess(response, user);
    }

    /**
     * 刷新Token
     */
    @GetMapping("/refreshToken")
    public Result<LoginVo> refreshToken(HttpServletResponse response) {
        UserEntity user = userServer.refreshToken();
        return loginSuccess(response, user);
    }

    private Result<LoginVo> loginSuccess(HttpServletResponse response, UserEntity user) {
        Long userId = user.getUserId();
        boolean admin = adminService.isAdmin(userId);
        String token = JwtTools.createToken(userId, admin, 7 * 24 * 60 * 60 * 1000L);
        JwtTools.addTokenToHttpServletResponse(response, token);
        LocalDateTime expireTime = LocalDateTime.now().plusDays(7);
        response.addHeader("expire-time", LocalDateTimeUtil.format(expireTime, DatePattern.NORM_DATETIME_PATTERN));

        LoginVo vo = UserMapstruct.INSTANCE.mapToLoginVo(user);
        vo.setToken(token);
        vo.setTokenExpireTime(expireTime);
        vo.setIsAdmin(admin);

        return Result.success(vo);
    }

    /**
     * 用户详情
     */
    @GetMapping("/details")
    public Result<UserVo> details(@RequestParam("userId") Long userId) {
        UserVo userInfo = userServer.details(userId);
        return Result.success(userInfo);
    }

}
